package com.abe.bathsystem.android.v3;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.abe.bathsystem.adapter.AbeCommonAdapter;
import com.abe.bathsystem.adapter.AbeViewHolder;
import com.abe.bathsystem.android.ResetActivity;
import com.abe.bathsystem.android.SplashActivity;
import com.abe.bathsystem.android.service.SocketService;
import com.abe.bathsystem.android.service.XGPushBathReceiver;
import com.abe.bathsystem.base.AutoMvpActivity;
import com.abe.bathsystem.base.ManagerLocalData;
import com.abe.bathsystem.contract.CommonContract;
import com.abe.bathsystem.contract.SerialPortContract;
import com.abe.bathsystem.contract.presenter.AdPresenter;
import com.abe.bathsystem.contract.presenter.BathPosPresenter;
import com.abe.bathsystem.contract.presenter.LoginPresenter;
import com.abe.bathsystem.contract.presenter.OrderPresenter;
import com.abe.bathsystem.contract.presenter.SerialPortPresenter;
import com.abe.bathsystem.contract.presenter.ServerPresenter;
import com.abe.bathsystem.contract.presenter.UploadPresenter;
import com.abe.bathsystem.contract.presenter.VersionPresenter;
import com.abe.bathsystem.entity.PushSocketData;
import com.abe.bathsystem.entity.ReqConstant;
import com.abe.bathsystem.entity.http.HttpGPushEntity;
import com.abe.bathsystem.entity.http.HttpNoticeEntity;
import com.abe.bathsystem.entity.http.HttpRoomEntity;
import com.abe.bathsystem.utils.AudioUtil;
import com.abe.bathsystem.utils.NormalUtils;
import com.abe.bathsystem.widget.OnOperateListener;
import com.abe.bathsystem.widget.button.LongTouchBtn;
import com.abe.bathsystem.widget.dialog.BathControlDialog;
import com.abe.bathsystem.widget.dialog.ChooseBathPosDialog;
import com.abe.bathsystem.widget.dialog.ChooseNoticeDialog;
import com.abe.bathsystem.widget.dialog.DialogContract;
import com.abe.bathsystem.widget.dialog.LoginMainDialog;
import com.abe.bathsystem.widget.dialog.LoginQuickDialog;
import com.abe.bathsystem.widget.dialog.MessageDialog;
import com.abe.bathsystem.widget.dialog.RoomDialog;
import com.abe.bathsystem.widget.dialog.ShowNoticeDialog;
import com.abe.bathsystem.widget.recyclerview.DefaultItemDecoration;
import com.abe.bathsystem.widget.text.LooperTextView;
import com.abe.bathsystem.widget.text.LooperView;
import com.abe.bathsystem.widget.video.AdVideoAutoPlayer;
import com.abe.libcore.utils.normal.CommonUtils;
import com.abe.libcore.utils.normal.EmptyUtils;
import com.abe.libcore.utils.normal.ThreadPoolUtils;
import com.abe.libcore.utils.normal.ToastUtils;
import com.bumptech.glide.Glide;
import com.maning.mndialoglibrary.MProgressDialog;
import com.tencent.android.tpush.XGPushConfig;

import net.yet.campusdev.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

public abstract class MainBathAbsActivity extends AutoMvpActivity implements CommonContract.ServerView, CommonContract.AdView,
        CommonContract.BathPosView, CommonContract.LoginView, CommonContract.OrderView,
        CommonContract.VersionView, OnOperateListener, SerialPortContract.SerialPortView, CommonContract.UploadView {

    //分发解析通知消息内容
    protected abstract void pushAction(HttpGPushEntity pushEntity);

    //提交所有洗浴用户
    protected abstract void submitAll(HttpRoomEntity roomEntity);

    //检查是否存在超时洗浴
    protected abstract void submitTimeOut30();

    //播放提示音
    protected abstract void StartMusic(int resId);

    protected int timeOutClient = 0;//循环上传个推ID计时标识
    protected boolean isClientUpSuccess = false;//个推ID上传成功标识
    protected boolean isActivityLive = false;//activity状态
    protected boolean isGetServerDataSuccess = false;//是否获取房间信息成功

    //dialog相关
    protected ChooseBathPosDialog dialog;//展示可使用选择洗浴位置
    protected LoginQuickDialog quickDialog;//快速登录弹窗（预约或者洗浴中）
    protected LoginMainDialog loginMainDialog;//无用户使用洗浴位置登录
    protected BathControlDialog controlDialog;//登录进入的控制面板
    protected RoomDialog roomDialog;//未注册房间提示面板
    protected ShowNoticeDialog showNoticeDialog;//展示公告详情面板
    protected ChooseNoticeDialog chooseNoticeDialog;//展示全部公告面板
    protected MessageDialog messageDialog;//公用信息提示面板

    //广播相关
    private MessageReceiver mMessageReceiver;//广播接收器
    public static final String REST_ACTIVITY = "com.abe.bath.reset";//重启广播

    protected int timeOutDialogShow;//检查无操作超时弹窗隐藏标识
    protected int READ_TIME_OUT = 30;//30秒超时
    protected boolean isPowerBreak;//是否断电标识
    protected static Date getSystemDataLocalTime;

    protected List<List<HttpNoticeEntity>> looperNoticeEntities = new ArrayList<>();
    protected AbeCommonAdapter noticeAdapter;

    protected boolean isCallBathPos = false;//是否正在获取服务器登记可用洗浴位置信息

    //获取服务器校准后真实时间
    public static Date getRealTime() {
        try {
            HttpRoomEntity roomEntity = ManagerLocalData.getRoomData();
            if (roomEntity == null) {
                return new Date();
            }
            getSystemDataLocalTime = getSystemDataLocalTime == null ? new Date(ManagerLocalData.getUpdateServerTime()) : getSystemDataLocalTime;
            Long time = new Date().getTime() - getSystemDataLocalTime.getTime();
            Long systemTime = Long.parseLong(roomEntity.getServerTime());
            //Date nowDate = new Date(systemTime + time);
            //CommonUtils.w(new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.CHINA).format(nowDate));
            //return nowDate;
            return new Date(systemTime + time);
        } catch (Exception e) {
            return new Date();
        }
    }

    //获取订单全提交时间，默认在凌晨12:20所有洗浴订单全部提交
    protected Date getCutAllTime(Date nowDate) {
        String ymd = new SimpleDateFormat("yyyyMMdd", Locale.CHINA).format(nowDate);
        //TODO 订单全提时间
        String hms = "00:20:00";
        Date cutDateTemp;
        try {
            cutDateTemp = new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.CHINA).parse(ymd + " " + hms);
        } catch (Exception e) {
            cutDateTemp = nowDate;
        }
        return cutDateTemp;
    }

    //获取不接受订单时间段-开始时间
    protected Date getStartCutTime(Date nowDate) {
        String ymd = new SimpleDateFormat("yyyyMMdd", Locale.CHINA).format(nowDate);
        //TODO 不接收订单开始时间
        String hms = "00:00:00";
        Date cutDateTemp;
        try {
            cutDateTemp = new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.CHINA).parse(ymd + " " + hms);
            CommonUtils.w("startCutTime=" + ymd + " " + hms);
        } catch (Exception e) {
            cutDateTemp = nowDate;
        }
        return cutDateTemp;
    }

    //获取不接受订单时间段-结束时间
    protected Date getEndCutTime(Date nowDate) {
        String ymd = new SimpleDateFormat("yyyyMMdd", Locale.CHINA).format(nowDate);
        //TODO 不接收订单结束时间
        String hms = "05:00:00";
        Date cutDateTemp;
        try {
            cutDateTemp = new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.CHINA).parse(ymd + " " + hms);
            CommonUtils.w("endCutTime=" + ymd + " " + hms);
        } catch (Exception e) {
            cutDateTemp = nowDate;
        }
        return cutDateTemp;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isActivityLive = false;
        destroyMessageReceiver();
    }

    @Override
    protected void initContent() {
        //调整为媒体最大音量
        if (AudioUtil.getInstance(this).getMediaVolume() < AudioUtil.getInstance(this).getMediaMaxVolume()) {
            AudioUtil.getInstance(this).setMediaVolume(AudioUtil.getInstance(this).getMediaMaxVolume());
        }
        isPowerBreak = true;
        isGetServerDataSuccess = false;
        isActivityLive = true;
        //推送接收器
        registerMessageReceiver();
        //通知列表
        initNoticeRV();
        //请求服务信息
        serverPresenter().getServerData();
    }

    private void initNoticeRV() {
        if (looperNoticeEntities == null) looperNoticeEntities = new ArrayList<>();
        noticeAdapter = new AbeCommonAdapter<List<HttpNoticeEntity>>(this, R.layout.item_recycler_v3_notice_looper, looperNoticeEntities) {

            @Override
            protected void convert(AbeViewHolder holder, final List<HttpNoticeEntity> entities, int position) {
                LooperView looperView = holder.getView(R.id.item_notice_looper);
                looperView.setTipList(entities, entities.size() > 3);
                looperView.setListener(new LooperView.OnChoosePosListener() {
                    @Override
                    public void onChoose(int pos) {
                        if (EmptyUtils.isEmpty(entities) || pos >= entities.size()) return;
                        HttpNoticeEntity noticeEntity = entities.get(pos);
                        showNoticeDialog = new ShowNoticeDialog(MainBathAbsActivity.this,
                                MainBathAbsActivity.this, noticeEntity);
                        showNoticeDialog.show();
                    }
                });
            }
        };
        itemNoticeRV.setLayoutManager(new LinearLayoutManager(this));
        itemNoticeRV.addItemDecoration(new DefaultItemDecoration(Color.TRANSPARENT, 1, 1));
        itemNoticeRV.setAdapter(noticeAdapter);
    }

    //轮询上传个推ID
    protected void timerTaskUploadClientRun() {
        if (!isClientUpSuccess) {
            timeOutClient++;
            //每两秒检查一次
            if (timeOutClient > 2) {
                HttpRoomEntity roomEntity = ManagerLocalData.getRoomData();
                String token = XGPushConfig.getToken(this);
                CommonUtils.w("activity-token:" + token);
                if (roomEntity != null && !TextUtils.isEmpty(token)) {
                    serverPresenter().uploadClientId(token);
                }
            }
        }
    }

    @Override
    public void onServerData(HttpRoomEntity entity) {
        //本地保存
        ManagerLocalData.saveData(entity, ManagerLocalData.LOCAL_TYPE_ROOM);
        //断电检查，true时提交所有订单
        if (isPowerBreak) {
            isPowerBreak = false;
            if (getIntent() != null && getIntent().getExtras() != null && getIntent().getExtras().containsKey("act")) {
                String x = getIntent().getExtras().getString("act", ResetActivity.class.getSimpleName());
                CommonUtils.w("act:" + x);
                //属于正常进入
                if (x.equals(SplashActivity.class.getSimpleName())) {
                    //再区分为断电后连电正常进入
                    if (!ManagerLocalData.isUpdateAPP()) {
                        ThreadPoolUtils.execute(new SubmitAll(entity));
                    } else {
                        //APP升级后正常进入
                        ManagerLocalData.updateAPP(false);
                    }
                }
            }
        }
        getSystemDataLocalTime = new Date();
        ManagerLocalData.saveUpdateServerTime(getSystemDataLocalTime.getTime());
        this.isGetServerDataSuccess = true;
        //初次加载广告数据
        adPresenter().getAdData();
        adPresenter().getNotice();
        //登录二维码
        //qrCodeBitmap = CodeUtils.createImage(entity.getLoginUrl(), 200, 200, BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground));
        //下载二维码
        Glide.with(this).load(entity.getDownloadImage()).centerCrop().into(itemDownloadQrCode);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                itemSettingRootView.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onRoomUnregistered() {
        //防止存在缓存
        ManagerLocalData.saveData(null, ManagerLocalData.LOCAL_TYPE_ROOM);
        itemSettingRootView.setVisibility(View.VISIBLE);
        roomDialog = new RoomDialog(this, this);
        roomDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                //得到房间信息，重启
                if (isGetServerDataSuccess) {
                    NormalUtils.resetApp();
                    return;
                }
                serverPresenter().getServerData();
            }
        });
        roomDialog.show();
    }

    @Override
    public void onUploadClientId(boolean isUploadSuccess) {
        isClientUpSuccess = isUploadSuccess;
    }

    //注册广播接收器
    private void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(XGPushBathReceiver.MESSAGE_RECEIVED_ACTION);
        filter.addAction(SocketService.SOCKET_MESSAGE);
        filter.addAction(REST_ACTIVITY);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    //释放广播接收
    private void destroyMessageReceiver() {
        if (mMessageReceiver != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
            mMessageReceiver = null;
        }
    }

    @OnClick(R.id.item_notice_more)
    public void onNoticeViewClicked() {
        if (looperNoticeEntities != null && looperNoticeEntities.size() > 0) {
            if (chooseNoticeDialog == null || !chooseNoticeDialog.isShowing()) {
                chooseNoticeDialog = new ChooseNoticeDialog(this, this, looperNoticeEntities.get(0));
                chooseNoticeDialog.setListener(new DialogContract.OnChooseNoticeListener() {
                    @Override
                    public void onChoose(HttpNoticeEntity entity) {
                        showNoticeDialog = new ShowNoticeDialog(MainBathAbsActivity.this,
                                MainBathAbsActivity.this, entity);
                        showNoticeDialog.show();
                    }
                });
                chooseNoticeDialog.show();
            }
        }
    }

    public class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null || intent.getExtras() == null || TextUtils.isEmpty(intent.getAction()))
                return;
            switch (intent.getAction()) {
                //重新加载Activity
                case REST_ACTIVITY: {
                    resetActivity();
                }
                break;
                //消息通知处理(个推)
                case XGPushBathReceiver.MESSAGE_RECEIVED_ACTION: {
                    final HttpGPushEntity entity = (HttpGPushEntity) intent.getExtras().getSerializable(XGPushBathReceiver.MESSAGE_KEY);
                    //推送为洗浴类型
                    if (entity != null && !TextUtils.isEmpty(entity.getType()) && entity.getType().equals("0")) {
                        switch (entity.getAction()) {
                            case ReqConstant.SYS_UPDATE: {
                                serverPresenter().getServerData();
                            }
                            break;
                            case ReqConstant.APP_UPDATE: {
                                versionPresenter().checkVersion(true);
                            }
                            break;
                            default: {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        pushAction(entity);
                                    }
                                });
                            }
                            break;
                        }
                    }
                }
                break;
                //消息通知处理（socket）
                case SocketService.SOCKET_MESSAGE: {
                    PushSocketData data = (PushSocketData) intent.getExtras().getSerializable(SocketService.SOCKET_MESSAGE);
                    if (data == null || TextUtils.isEmpty(data.getType())) return;
                    switch (data.getType()) {
                        case SocketService.SOCKET_STATUS: {
                            final String message = (String) data.getInfo();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtils.show(message);
                                }
                            });
                        }
                        break;
                        case SocketService.SOCKET_MSG: {
                            final HttpGPushEntity entity = (HttpGPushEntity) data.getInfo();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    pushAction(entity);
                                }
                            });
                        }
                        break;
                    }
                }
                break;
            }
        }
    }

    //自动提交所有
    class SubmitAll implements Runnable {

        HttpRoomEntity roomEntity;

        SubmitAll(HttpRoomEntity roomEntity) {
            this.roomEntity = roomEntity;
        }

        @Override
        public void run() {
            submitAll(roomEntity);
        }
    }

    //去掉弹窗显示
    protected void dismissDialog() {
        dismissDialog(showNoticeDialog);
        dismissDialog(chooseNoticeDialog);
        dismissDialog(dialog);
        dismissDialog(quickDialog);
        dismissDialog(loginMainDialog);
        dismissDialog(controlDialog);
        dismissDialog(roomDialog);
        dismissDialog(messageDialog);
    }

    //用于无操作计时
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //有按下动作时取消定时
                onOperate();
                break;
            case MotionEvent.ACTION_MOVE:
                //在按住滑动时取消定时
                onOperate();
                break;
            case MotionEvent.ACTION_UP:
                //抬起时启动定时
                onOperate();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 监听Back键按下事件,方法2:
     * 注意:
     * 返回值表示:是否能完全处理该事件
     * 在此处返回false,所以会继续传播该事件.
     * 在具体项目中此处的返回值视情况而定.
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            //CommonUtils.w("可以在此屏蔽返回菜单键,限制用户只能点击进入登录页");
            onBackPressed();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void onBackPressed() {
    }

    @Override
    public ServerPresenter serverPresenter() {
        return (ServerPresenter) getPresenter(ServerPresenter.class);
    }

    @Override
    public AdPresenter adPresenter() {
        return (AdPresenter) getPresenter(AdPresenter.class);
    }

    @Override
    public BathPosPresenter bathPosPresenter() {
        return (BathPosPresenter) getPresenter(BathPosPresenter.class);
    }

    @Override
    public LoginPresenter loginPresenter() {
        return (LoginPresenter) getPresenter(LoginPresenter.class);
    }

    @Override
    public OrderPresenter orderPresenter() {
        return (OrderPresenter) getPresenter(OrderPresenter.class);
    }

    @Override
    public SerialPortPresenter serialPortPresenter() {
        return (SerialPortPresenter) getPresenter(SerialPortPresenter.class);
    }

    @Override
    public VersionPresenter versionPresenter() {
        return (VersionPresenter) getPresenter(VersionPresenter.class);
    }

    @Override
    public UploadPresenter uploadPresenter() {
        return (UploadPresenter) getPresenter(UploadPresenter.class);
    }

    @Override
    public void onFinish(Object type) {
        if (type.equals(OrderPresenter.class.getSimpleName() + "-orderStart")) {
            MProgressDialog.dismissProgress();
        }
    }

    @Override
    public void onFailure(Object type) {
        if (type.equals(BathPosPresenter.class.getSimpleName() + "-getRoomStatus")) {
            localSendMessage(APP_TOAST, "获取房间洗浴位置失败");
        } else if (type.equals(OrderPresenter.class.getSimpleName() + "-orderEnd")) {
            localSendMessage(APP_TOAST, "访问洗浴结束服务失败");
        } else if (type.equals(ServerPresenter.class.getSimpleName() + "-getRoomData")) {
            localSendMessage(APP_TOAST, "获取二维码等数据失败");
        }
    }

    class BaseHandler extends Handler {
        BaseHandler(Looper looper) {
            super(looper);
        }

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case APP_TOAST: {
                    if (!TextUtils.isEmpty(msg.obj.toString())) {
                        ToastUtils.show(msg.obj.toString());
                    }
                }
                break;
                case START_MUSIC: {
                    if (!TextUtils.isEmpty(msg.obj.toString())) {
                        String resIdStr = msg.obj.toString();
                        int resId = Integer.parseInt(resIdStr);
                        StartMusic(resId);
                    }
                }
                break;
                case CALL_BATH_POS: {
                    isCallBathPos = false;
                }
                break;
            }
        }
    }

    protected BaseHandler getHandler() {
        return new BaseHandler(Looper.getMainLooper());
    }

    protected void localSendMessage(int what, Object object) {
        Message message = new Message();
        message.obj = object;
        message.what = what;
        getHandler().sendMessage(message);
    }

    protected void dismissDialog(Dialog dialog) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    protected void resetActivity() {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_v3_main_bath;
    }

    @BindView(R.id.item_txt_gg)
    LooperTextView itemTxtGg;
    @BindView(R.id.item_ad_video)
    AdVideoAutoPlayer itemAdVideo;
    @BindView(R.id.item_ad_image)
    ImageView itemAdImage;
    @BindView(R.id.item_ad_cover)
    ImageView itemAdCover;
    @BindView(R.id.item_download_qr_code)
    ImageView itemDownloadQrCode;
    @BindView(R.id.item_ad_time)
    TextView itemAdTime;
    @BindView(R.id.item_lock_time)
    TextView itemLockTime;
    @BindView(R.id.item_check_version)
    TextView itemCheckVersion;
    @BindView(R.id.item_serial_port)
    TextView itemSerialPort;
    @BindView(R.id.item_service_url)
    TextView itemServiceUrl;
    @BindView(R.id.item_locker)
    TextView itemLocker;
    @BindView(R.id.item_limit_bath)
    TextView itemLimitBath;
    @BindView(R.id.item_btn_setting)
    LongTouchBtn itemBtnSetting;
    @BindView(R.id.item_setting_root_view)
    View itemSettingRootView;
    @BindView(R.id.item_show_serial_view)
    View itemShowSerialView;
    @BindView(R.id.item_device_mac)
    TextView itemDeviceMac;
    @BindView(R.id.item_notice_rv)
    RecyclerView itemNoticeRV;

    protected static final int APP_TOAST = 0x001;
    protected static final int START_MUSIC = 0x002;
    protected static final int CALL_BATH_POS = 0x003;
}